<?php
/**
* @version   $Id: joslang.php 8 2009-03-09 17:01:54Z edo888 $
* @package   JosLang
* @copyright Copyright (C) 2008 David Thomas <davidwhthomas@gmail.com>, Edvard Ananyan <edo888@gmail.com>. All rights reserved.
* @license   http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/

defined( '_JEXEC' ) or die( 'Restricted access' );

jimport( 'joomla.plugin.plugin' );

/**
 * JosLang plugin
 *
 */
class  plgSystemJosLang extends JPlugin {
    /**
     * Current language
     *
     * @var string
     */
    var $_lang;

    /**
     * Constructor
     *
     * For php4 compatability we must not use the __constructor as a constructor for plugins
     * because func_get_args ( void ) returns a copy of all passed arguments NOT references.
     * This causes problems with cross-referencing necessary for the observer design pattern.
     *
     * @access protected
     * @param  object $subject The object to observe
     * @param  array  $config  An array that holds the plugin configuration
     * @since  1.0
     */
    function plgSystemJosLang(& $subject, $config) {
        // check to see if we are on frontend to execute plugin
        global $mainframe;
        if($mainframe->isAdmin())
            return;

        parent::__construct($subject, $config);
        $this->_lang = JRequest::getVar('joslang', $this->params->get('default_lang'), 'COOKIE');
    }

    /**
     * Routes URLs
     *
     * @access public
     */
    function onAfterInitialise() {
        global $mainframe;

        $uri    =& JURI::getInstance();
        $router =& $mainframe->getRouter();

        $router->attachBuildRule('plgSystemJosLang::buildJosLang');
        $router->attachParseRule('plgSystemJosLang::parseJosLang');

    }

    /**
     * Translating the site
     *
     * @access public
     */
    function onAfterRender() {
        $body = JResponse::getBody();
        $this->showLanguageSelector($body);
        $this->doTranslate($body, $this->_lang);
        JResponse::setBody($body);

    }

    /**
     * Parses JosLang syntax
     *
     * @access public
     */
    function doTranslate(& $content, $lang) {
        // strip current language open/close brackets
        $content = preg_replace('/(\['.$lang.'\])|(\[\/'.$lang.'\])/', '', $content);

        // strip all other language texts
        if(function_exists('mb_ereg_replace'))
            $content = mb_ereg_replace('\[..\]((.|\R)*?)\[\/..\]', '', $content, 'sr');
        else
            $content = preg_replace('/\[..\]((.|\R)*?)\[\/..\]/', '', $content);

    }

    /**
     * Replaces {joslang_selector} with language selector
     *
     * @access public
     */
    function showLanguageSelector(& $content) {
        $languages = rtrim($this->params->get('language_names'));
        $languages = explode("\n", $languages);

        $language_selector = '<script type="text/javascript">';
        $language_selector .= 'function createCookie(name,value,days){if(days){var date=new Date();date.setTime(date.getTime()+(days*24*60*60*1000));var expires="; expires="+date.toGMTString();}else var expires="";document.cookie=name+"="+value+expires+"; path=/";}';
        $language_selector .= 'function changeLanguage(lang) {var prev_lang="'.$this->_lang.'";if(lang.value == prev_lang || lang.value == "")return;else{createCookie("joslang", lang.value, 365);location.pathname=location.pathname.replace("/"+prev_lang, "/"+lang.value);}}';
        $language_selector .= '</script>';

        $language_selector .= '<select onChange="changeLanguage(this)">';
        $language_selector .= '<option value="">Select Language</option>';

        foreach($languages as $lang) {
            list($lang_code, $lang) = explode('=', $lang);
            $language_selector .= '<option value="'.$lang_code.'">'.$lang.'</option>';
        }

        $language_selector .= '</select>';

        // replace {joslang_select} with language selector
        $content = preg_replace('/{joslang_select}/', $language_selector, $content);

    }

    /**
     * SEF language builder
     *
     * @access public
     * @static
     * @param $router object of JRouter class
     * @param $uri object of JURI class
     */
    static function buildJosLang(& $router, & $uri) {
        if($router->getMode() == JROUTER_MODE_RAW)
            return;

        $lang = JRequest::getVar('joslang', 'en', 'COOKIE');
        $uri->setPath($uri->getPath().'/'.$lang);
    }

    /**
     * SEF language parser
     *
     * @access public
     * @static
     * @param $router object of JRouter class
     * @param $uri object of JURI class
     */
    static function parseJosLang(& $router, & $uri) {
        if($router->getMode() == JROUTER_MODE_RAW)
            return array();

        $lang = JRequest::getVar('joslang', 'en', 'COOKIE');

        $segments = explode('/', $uri->getPath());
        foreach($segments as $i => $segment)
            if($segment == $lang)
                unset($segments[$i]);

        $uri->setPath(implode('/', $segments));

        return array();
    }
}